﻿@COFE ?= {}

$ = jQuery
Entry = COFE.Entry
EntryItem = COFE.EntryItem
EntryList = COFE.EntryList
utils = COFE.utils

# CONTROLLER - Base class for represent a number of EntryItems (controller), 
#              which is Entries (model) generated from EntryList (model).
#     params - @el, @App (for listening pathChanged event)

class EntryItemListBase extends Spine.Controller  
  constructor : () ->
    @childElementKey = "<div>"
    @childTemplateKey = "#entryItemTemplate" 
    @entryItems = [] 
    super

  # Convert EntryList (model)'s entries to EntryItem (controller), 
  # -> store it to @entryItems, @folderItems and @fileItems  
  # -> raise updated event.
  update : () =>        
    #unbind the entryItem.click events.
    eItem.unbind("clicked") for eItem in @entryItems        

    @entryItems = (for entry in @entryList.entries
      EntryItem.init({
        App: @App
        entry: entry
        templateKey: @childTemplateKey
        el : $(@childElementKey)
      }))

    #bind the entryItem.click events.
    eItem.bind("clicked", @onItemClicked) for eItem in @entryItems                          
      

    @folderItems = []
    @fileItems = []
    (if entryItem.entry.basetype is "folder" then @folderItems else @fileItems).push entryItem for entryItem in @entryItems
    
    @status = "done"
    $.mobile.hidePageLoadingMsg()
    @trigger("updated", @)  
  
  # Find an entry from this entry list.
  indexOf : (entry) =>
    for entryItem, i in @entryItems
      if entryItem.entry.path is entry.path
        return i
    return -1

  # handles App.pathChanged event.
  # This event is bound in customer method, e.g. EntryList or EntryDetailList    
  # App.pathChanged event -> onPathChanged() -> changePath() -> @entryList = EntryList.fromPath() ->
  #    Cached -> update()
  # NotCached -> @entryList.fetch() -> (when fetched) -> update()
  onPathChanged : (sender, path) =>    
    @changePath(path)

  # Overridable, called by onPathChanged() after App.pathChanged event (if bound) is raised.
  changePath : (path) =>   
    #unbind last entryList if exits
    @entryList?.unbind("fetched", @update)    

    #initalize new entryList
    @entryList = EntryList.fromLink(path)
     
    $.mobile.showPageLoadingMsg()    
    if @entryList.status isnt "ready"           
      @entryList.bind("fetched", @update)      
      @entryList.fetch()   
    else
      @update()

  # handles EntryItem.clicked event.
  onItemClicked : (sender) =>
    @itemClicked(sender, sender.entry)
  
  # Overridable, called by onItemClicked() after user clicked on an item, 
  itemClicked : (entryItem, entry) =>
    @

  init : ->      
    

 

COFE.EntryItemListBase = EntryItemListBase
